/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * This is the main POS screen that performs the check out. AddItems, search, pay, view bill etc are supported
 *
 * Created on Mar 14, 2011, 3:16:54 PM
 */

package pos.ui.screen;
import java.awt.Dialog.ModalExclusionType;
import java.awt.Toolkit;
import java.sql.Date;
import java.util.ArrayList;
import java.util.ListIterator;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import pos.ads.AdsManager;
import pos.ads.Advertisement;
import pos.auth.Authentication;
import pos.control.ItemViewControl;
import pos.control.OrderControl;
import pos.control.PurchasedItemControl;
import pos.entity.Item;
import pos.control.TaxControl;
import pos.entity.Order;
import pos.entity.PurchasedItem;
import pos.storage.db.mysql.SelectQueryTableModel;
import pos.storage.db.sql.SQL;
import pos.util.IDGenerator;
import pos.entity.PriceAdjustment;
import pos.entity.PriceAdjustment.PriceAdjustmentType;
/**
 *
 * @author vmm
 */
public class Customer extends javax.swing.JFrame {

    SelectQueryTableModel sTableModel = new SelectQueryTableModel();

    LogIn loginParent = new LogIn();

    PriceAdjustment _currDiscount;
    ShippingInfo si = null;
    Bill billObj = null;
    //Order entity for the current set of purchased items
    private Order currOrder;

    //The purchased item list selected in the screen
    ArrayList<PurchasedItem> purchasedItemList= new ArrayList<PurchasedItem>();
    
    /* adding ads manager class here */
    static int banners = 3;

    static String pathToAdsDir = pos.Pos.conf.getExtDirs().get("banners");


    static ArrayList<Advertisement> adverts = new ArrayList<Advertisement>(banners);
    static AdsManager adsMan = new AdsManager(pathToAdsDir, banners);

    public LogIn getLoginParent() {
        return loginParent;
    }

    public void setLoginParent(LogIn loginParent) {
        this.loginParent = loginParent;
    }

    /** Creates new form Customer */
    public Customer() {
        setTitle("POS Screen");
        initComponents();
        setSize(924,700);
        TableSelectionListener listener = new TableSelectionListener();
        jTable1.getSelectionModel().addListSelectionListener(listener);
        setIconImage(Toolkit.getDefaultToolkit().getImage("..\\pos\\images\\JavaCup.gif"));
        this.discountBtn.setEnabled(false);
        this.jButton7.setEnabled(false);
//        pathToAdsDir = pos.Pos.conf.getExtDirs().get("banners");
        this.initialiseAds();
    }
    
    /**
     * 
     * @param bannerPath 
     */
    public Customer(String bannerPath){
        setTitle("POS Screen");
        initComponents();
        setSize(860,700);
        TableSelectionListener listener = new TableSelectionListener();
        jTable1.getSelectionModel().addListSelectionListener(listener);
        setIconImage(Toolkit.getDefaultToolkit().getImage("..\\pos\\images\\JavaCup.gif"));
        this.discountBtn.setEnabled(false);
        this.jButton7.setEnabled(false);
        pathToAdsDir = bannerPath;
        this.initialiseAds();
    }
    
    /**
     * generate random ads in ads space
     */
    private void initialiseAds() {
        try {
            adverts = adsMan.getAdsPool();
            adSpace1.setIcon(new ImageIcon(adverts.get(adsMan.getAdsArr(0)).getLocatoin()));
            adSpace2.setIcon(new ImageIcon(adverts.get(adsMan.getAdsArr(1)).getLocatoin()));
            adSpace3.setIcon(new ImageIcon(adverts.get(adsMan.getAdsArr(2)).getLocatoin()));
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Notice: Banner folder not found: " + pathToAdsDir);
        }
    }
    /**
     * Adds the discount column renderer
     * @param jTable1
     * @param discCol 
     */
    private void addDiscountColumnRend(JTable jTable1, TableColumn discCol){
        JComboBox comboBox = new JComboBox();
        comboBox.addItem("Snowboarding");
        comboBox.addItem("Rowing");
        discCol.setCellEditor(new DefaultCellEditor(comboBox));
        
        //Set up tool tips for the sport cells.
        DefaultTableCellRenderer renderer =
                new DefaultTableCellRenderer();
        renderer.setToolTipText("Click for combo box");
        discCol.setCellRenderer(renderer);
        jTable1.revalidate();
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jTextField1 = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        adSpace1 = new javax.swing.JLabel();
        adSpace2 = new javax.swing.JLabel();
        adSpace3 = new javax.swing.JLabel();
        deleteBtn = new javax.swing.JButton();
        clearAll = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        bill = new javax.swing.JButton();
        btnClear = new javax.swing.JButton();
        btn7 = new javax.swing.JButton();
        btn8 = new javax.swing.JButton();
        btn4 = new javax.swing.JButton();
        btn9 = new javax.swing.JButton();
        btn6 = new javax.swing.JButton();
        btn5 = new javax.swing.JButton();
        btn1 = new javax.swing.JButton();
        btn2 = new javax.swing.JButton();
        btnDeleteLastChar = new javax.swing.JButton();
        btn3 = new javax.swing.JButton();
        btn0 = new javax.swing.JButton();
        Shipping = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel5 = new javax.swing.JPanel();
        discountBtn = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                onWindowClose(evt);
            }
        });
        getContentPane().setLayout(null);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel1.setLayout(null);

        jTextField1.setFont(new java.awt.Font("Tahoma", 0, 24));
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        jPanel1.add(jTextField1);
        jTextField1.setBounds(10, 30, 190, 50);

        jButton3.setFont(new java.awt.Font("Tahoma", 0, 24));
        jButton3.setText("Add Item");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton3);
        jButton3.setBounds(10, 90, 190, 80);

        jButton2.setFont(new java.awt.Font("Tahoma", 0, 24));
        jButton2.setText("Search");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton2);
        jButton2.setBounds(10, 190, 190, 80);

        jButton1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jButton1.setLabel("Pay");
        jButton1.setPreferredSize(new java.awt.Dimension(73, 37));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1);
        jButton1.setBounds(10, 290, 190, 80);

        jPanel3.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel5.setText("Ad Space");
        jLabel5.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 184, Short.MAX_VALUE)
                    .addComponent(adSpace2, javax.swing.GroupLayout.DEFAULT_SIZE, 184, Short.MAX_VALUE)
                    .addComponent(adSpace1, javax.swing.GroupLayout.DEFAULT_SIZE, 184, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(adSpace1, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addComponent(adSpace2, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27))
        );

        jPanel1.add(jPanel3);
        jPanel3.setBounds(210, 380, 210, 270);

        deleteBtn.setFont(new java.awt.Font("Tahoma", 0, 24));
        deleteBtn.setText("Delete Item");
        deleteBtn.setFocusTraversalPolicyProvider(true);
        deleteBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteBtnActionPerformed(evt);
            }
        });
        jPanel1.add(deleteBtn);
        deleteBtn.setBounds(10, 480, 190, 80);

        clearAll.setFont(new java.awt.Font("Tahoma", 0, 24));
        clearAll.setText("Clear All");
        clearAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearAllActionPerformed(evt);
            }
        });
        jPanel1.add(clearAll);
        clearAll.setBounds(10, 570, 190, 80);

        jLabel3.setText("Enter Product Code:");
        jPanel1.add(jLabel3);
        jLabel3.setBounds(10, 4, 110, 20);

        bill.setFont(new java.awt.Font("Tahoma", 0, 24));
        bill.setText("Bill");
        bill.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                billActionPerformed(evt);
            }
        });
        jPanel1.add(bill);
        bill.setBounds(10, 390, 190, 80);

        btnClear.setFont(new java.awt.Font("Tahoma", 0, 24));
        btnClear.setText("Clear");
        btnClear.setDefaultCapable(false);
        btnClear.setMargin(new java.awt.Insets(3, 3, 3, 3));
        btnClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnClearActionPerformed(evt);
            }
        });
        jPanel1.add(btnClear);
        btnClear.setBounds(330, 210, 90, 60);

        btn7.setFont(new java.awt.Font("Tahoma", 0, 24));
        btn7.setText("7");
        btn7.setDefaultCapable(false);
        btn7.setMargin(new java.awt.Insets(3, 3, 3, 3));
        btn7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn7ActionPerformed(evt);
            }
        });
        jPanel1.add(btn7);
        btn7.setBounds(210, 30, 70, 60);

        btn8.setFont(new java.awt.Font("Tahoma", 0, 24));
        btn8.setText("8");
        btn8.setDefaultCapable(false);
        btn8.setMargin(new java.awt.Insets(3, 3, 3, 3));
        btn8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn8ActionPerformed(evt);
            }
        });
        jPanel1.add(btn8);
        btn8.setBounds(280, 30, 70, 60);

        btn4.setFont(new java.awt.Font("Tahoma", 0, 24));
        btn4.setText("4");
        btn4.setDefaultCapable(false);
        btn4.setMargin(new java.awt.Insets(3, 3, 3, 3));
        btn4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn4ActionPerformed(evt);
            }
        });
        jPanel1.add(btn4);
        btn4.setBounds(210, 90, 70, 60);

        btn9.setFont(new java.awt.Font("Tahoma", 0, 24));
        btn9.setText("9");
        btn9.setDefaultCapable(false);
        btn9.setMargin(new java.awt.Insets(3, 3, 3, 3));
        btn9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn9ActionPerformed(evt);
            }
        });
        jPanel1.add(btn9);
        btn9.setBounds(350, 30, 70, 60);

        btn6.setFont(new java.awt.Font("Tahoma", 0, 24));
        btn6.setText("6");
        btn6.setDefaultCapable(false);
        btn6.setMargin(new java.awt.Insets(3, 3, 3, 3));
        btn6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn6ActionPerformed(evt);
            }
        });
        jPanel1.add(btn6);
        btn6.setBounds(350, 90, 70, 60);

        btn5.setFont(new java.awt.Font("Tahoma", 0, 24));
        btn5.setText("5");
        btn5.setDefaultCapable(false);
        btn5.setMargin(new java.awt.Insets(3, 3, 3, 3));
        btn5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn5ActionPerformed(evt);
            }
        });
        jPanel1.add(btn5);
        btn5.setBounds(280, 90, 70, 60);

        btn1.setFont(new java.awt.Font("Tahoma", 0, 24));
        btn1.setText("1");
        btn1.setDefaultCapable(false);
        btn1.setMargin(new java.awt.Insets(3, 3, 3, 3));
        btn1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn1ActionPerformed(evt);
            }
        });
        jPanel1.add(btn1);
        btn1.setBounds(210, 150, 70, 60);

        btn2.setFont(new java.awt.Font("Tahoma", 0, 24));
        btn2.setText("2");
        btn2.setDefaultCapable(false);
        btn2.setMargin(new java.awt.Insets(3, 3, 3, 3));
        btn2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn2ActionPerformed(evt);
            }
        });
        jPanel1.add(btn2);
        btn2.setBounds(280, 150, 70, 60);

        btnDeleteLastChar.setFont(new java.awt.Font("Tahoma", 0, 24));
        btnDeleteLastChar.setText("<-");
        btnDeleteLastChar.setDefaultCapable(false);
        btnDeleteLastChar.setMargin(new java.awt.Insets(3, 3, 3, 3));
        btnDeleteLastChar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteLastCharActionPerformed(evt);
            }
        });
        jPanel1.add(btnDeleteLastChar);
        btnDeleteLastChar.setBounds(280, 210, 50, 60);

        btn3.setFont(new java.awt.Font("Tahoma", 0, 24));
        btn3.setText("3");
        btn3.setDefaultCapable(false);
        btn3.setMargin(new java.awt.Insets(3, 3, 3, 3));
        btn3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn3ActionPerformed(evt);
            }
        });
        jPanel1.add(btn3);
        btn3.setBounds(350, 150, 70, 60);

        btn0.setFont(new java.awt.Font("Tahoma", 0, 24));
        btn0.setText("0");
        btn0.setDefaultCapable(false);
        btn0.setMargin(new java.awt.Insets(3, 3, 3, 3));
        btn0.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn0ActionPerformed(evt);
            }
        });
        jPanel1.add(btn0);
        btn0.setBounds(210, 210, 70, 60);

        Shipping.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        Shipping.setText("Shipping");
        Shipping.setPreferredSize(new java.awt.Dimension(73, 37));
        Shipping.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ShippingActionPerformed(evt);
            }
        });
        jPanel1.add(Shipping);
        Shipping.setBounds(220, 290, 190, 80);

        getContentPane().add(jPanel1);
        jPanel1.setBounds(488, 1, 430, 730);

        jTable1.setFont(new java.awt.Font("Tahoma", 0, 24));
        jTable1.setModel(sTableModel);
        jTable1.setRowHeight(45);
        jScrollPane2.setViewportView(jTable1);

        discountBtn.setFont(new java.awt.Font("Tahoma", 0, 24));
        discountBtn.setText("Discount");
        discountBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                discountBtnActionPerformed(evt);
            }
        });

        jButton7.setFont(new java.awt.Font("Tahoma", 0, 24));
        jButton7.setText("New Customer");
        jButton7.setDefaultCapable(false);
        jButton7.setMargin(new java.awt.Insets(3, 3, 3, 3));
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        jButton6.setFont(new java.awt.Font("Tahoma", 0, 24));
        jButton6.setText("Help");
        jButton6.setDefaultCapable(false);
        jButton6.setMargin(new java.awt.Insets(3, 3, 3, 3));
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addComponent(discountBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(51, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(discountBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(15, Short.MAX_VALUE))
        );

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 24));
        jLabel2.setText("Order");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(217, 217, 217)
                        .addComponent(jLabel2))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 494, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(75, 75, 75))
        );

        getContentPane().add(jPanel2);
        jPanel2.setBounds(10, 1, 470, 720);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        ItemViewControl adminControl = new ItemViewControl();
        String itemCode = jTextField1.getText();
        if(itemCode == null || itemCode.isEmpty()){
            return;
        }
        String sql = SQL.SelectItemWithCritera.replace("(?)", itemCode);
        adminControl.genTable(sTableModel,sql); 
     
        addPurchaseItem();
        addLatValues();
        
        jTable1.revalidate();
        TableColumn tc = jTable1.getColumnModel().getColumn(1);
        jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tc.setPreferredWidth(200);
        //billAmountLbl.setText((adminControl.getBill(sTableModel).toString()));
    }//GEN-LAST:event_jButton3ActionPerformed
    
    /**
     * Calculates the discount value and updates the JTable
     */
    public void addLatValues(){
        int size = purchasedItemList.size();
        PurchasedItemControl pic = new PurchasedItemControl();
        pic.updatePurchasedItemPriceAttributes(purchasedItemList);
        updateJTable();
    }
    /**
     * Updates the JTable with the latest calculation
     */
    public void updateJTable(){
        PurchasedItemControl pic = new PurchasedItemControl();
        pic.updatePurchasedItemPriceAttributes(purchasedItemList);
        int size = purchasedItemList.size();
        for(int i=0; i<size; i++){
            PurchasedItem pi = purchasedItemList.get(i);
            sTableModel.setValueAt(i, 2, pi.getBasePrice());
            sTableModel.setValueAt(i, 3, pi.getPriceAdjustedAmount());
            sTableModel.setValueAt(i, 4, pi.getTotalTaxes());
            sTableModel.setValueAt(i, 5, pi.getTotalPrice());
            sTableModel.setValueAt(i, 6, pi.getPurchaseItemId());
            
        }
    }
    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        processPurchase();
    }//GEN-LAST:event_jButton1ActionPerformed
    /**
     * Process the purchase request it adds the order object
     */
    public void processPurchase(){
        Payment pay = new Payment();
        currOrder = getOrder(null);
        pay.setOrder(currOrder);
        si = new ShippingInfo();
        billObj = new Bill(currOrder);
        
        si.setOrder(currOrder);
        pay.setVisible(true);
    }
    
    /**
     * Adds the purchase item object
     */
    private void addPurchaseItem(){
        try{
            PurchasedItem pi = new PurchasedItem();
        int i = sTableModel.getRowCount() - 1;
        pi.setPurchaseItemId(IDGenerator.getID());
            pi.setItemId((Long)sTableModel.getValueAt(i, 0));
            pi.setName((String)sTableModel.getValueAt(i, 1));
            pi.setBasePrice((Double)sTableModel.getValueAt(i, 2));//2 index in the jTable is base price
            pi.setDateModified(new Date(System.currentTimeMillis()));
            pi.setDateTimeCreated(new Date(System.currentTimeMillis()));
            Object obj1 = sTableModel.getValueAt(i, 3);//Discount
            if(obj1 != null){
                pi.setPriceAdjustedAmount(i);
            }
            obj1 = sTableModel.getValueAt(i, 5);//Total
            if(obj1 != null){
                pi.setTotalPrice((Double)obj1);
            }
            pi.setIsToBePicked(0);
            purchasedItemList.add(pi);
        }catch(Exception e){
            System.out.println("Error while adding items " + e.getMessage());
            //e.printStackTrace();
        }
        
    }
    /**
     * Returns the purchased Items selected in the cart
     * @param itemList
     * @return 
     */
    private ArrayList getPurchasedItems(ArrayList<Item> itemList){
        int rowC = itemList.size();
        ArrayList<PurchasedItem> purchaseItemList = new ArrayList();
        for(int i=0; i<rowC; i++){
            PurchasedItem pi = new PurchasedItem();
            Item it = itemList.get(i);
            pi.setItemId(it.getID());
            pi.setBasePrice(it.getBasePrice());
            pi.setDateModified(new Date(System.currentTimeMillis()));
            pi.setDateTimeCreated(new Date(System.currentTimeMillis()));
            pi.setName(it.getName());
            //pi.setPriceAdjustedAmount(it.getPriceAdjustedAmount());
            //pi.setTotalPrice(it.getTotalPrice());
            
            pi.setIsToBePicked(0);
            purchaseItemList.add(pi);
        }
        return purchaseItemList;
    }
    /**
     * Returns the order object for the selected items
     * @param itemList
     * @return 
     */
    public Order getOrder(ArrayList<Item> itemList){
        Order order = new Order();
        order.setOrderId(IDGenerator.getID());
        order.setCustomerId(0);
        order.setDateTimeCreated(new Date(System.currentTimeMillis()));        
        if(itemList == null){
            order.setPurchasedItems(purchasedItemList);
        }
        else{
            ArrayList<PurchasedItem> newPurchasedItemList = getPurchasedItems(itemList);
            order.setPurchasedItems(newPurchasedItemList);
        }
        order.setOrderDateModified(new Date(System.currentTimeMillis()));
        order.setOrderDateTime(new Date(System.currentTimeMillis()));
        order.setOrderTakenByEmployeeId(0);
        order.setOrderTotalAdjustedAmount(0);
        order.setOrderTotalTaxes(0);
        order.setOrderTotalBasePrice(0);
        order.setOrderTotalPrice(0);
        if(itemList != null){
            order.setOrderTransactionSource("Desktop");
        }
        else{
            order.setOrderTransactionSource("POS");
        }
        
        return order;
    }
    private void discountBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_discountBtnActionPerformed
        //Get information for the discount
        PriceAdjustment discount = openCustomerDiscountDialog();

        //If nothing returned
        if (discount == null) {
            return;
        }
        
        //Update the purchased item with the discount
        addPriceAdjustmentToPurchasedItem(discount);

        //Update the price fields for all purchased items
        PurchasedItemControl pItemControl = new PurchasedItemControl();

        pItemControl.updatePurchasedItemPriceAttributes(purchasedItemList);

        //Test update order total prices
        OrderControl ordCtl = new OrderControl();
        ordCtl.updateOrderTotalPrices(currOrder, purchasedItemList);
        updateJTable();
    }//GEN-LAST:event_discountBtnActionPerformed

    private void deleteBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteBtnActionPerformed

        try {
            int rows[] = jTable1.getSelectedRows();

            //Ensure selecte rows is not less than 0
            if (rows.length <= 0 || rows.length > 1) {
                System.out.println("No purchased items to delete");
                return;
            }

            //Determine column number for relevant jTable fields
            int purchasedItemIdColumn = -1;

            //Check each column in the table for the appropriate name
            for (int colNum = 0; colNum <= jTable1.getColumnCount() - 1; colNum++) {

                if (jTable1.getColumnName(colNum).equals("PItemId")) {
                    purchasedItemIdColumn = colNum;
                }
            }

            //Confirm that columns were found, if not, provide message and return
            if (purchasedItemIdColumn == -1) {

                JOptionPane.showMessageDialog(this,
                        "Design time error: Missing column",
                        "Error",
                        JOptionPane.ERROR_MESSAGE);

                return;
            }

            //Remove all selected rows
            for(int j = 0; j < rows.length; j++) {

                //Get the purchasedItem to remove
                PurchasedItem pItemToRemove = retrievePurchasedItem((Long)jTable1.getValueAt(rows[j], purchasedItemIdColumn));

                ListIterator pItemListIter = purchasedItemList.listIterator();

                while (pItemListIter.hasNext()) {

                    PurchasedItem pItem = (PurchasedItem)pItemListIter.next();
                    if (pItem.getPurchaseItemId() == pItemToRemove.getPurchaseItemId()) {

                        pItemListIter.remove();
                        System.out.println("Item removed");
                        break;
                    }
                }

                sTableModel.removeAt(rows[j]);

                for (PurchasedItem item : purchasedItemList) {

                    System.out.println("PI info" + item.getPurchaseItemId());
                }

                jTable1.revalidate();
            }
        }
        catch (Exception e) {

            System.out.println("Exception as a result of delete");
        }

    }//GEN-LAST:event_deleteBtnActionPerformed

    private void clearAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearAllActionPerformed
        //Clears all the component values
        sTableModel.removeAll();
        purchasedItemList.removeAll(purchasedItemList);
        jTable1.revalidate();
        jTextField1.setText(null);
        _currDiscount = null;
        currOrder = null;
        //billAmountLbl.setText(null);
    }//GEN-LAST:event_clearAllActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        new RegisterNewCustomer().setVisible(true);
}//GEN-LAST:event_jButton7ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        Search search = new Search();
        search.setParentWindow(this);
        this.setVisible(false);
        search.setItemTextField(jTextField1);
        search.setVisible(true);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void onWindowClose(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_onWindowClose
        loginParent.setVisible(true);
    }//GEN-LAST:event_onWindowClose

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        String action = "HELP_CUSTOMER";
        if(!Authentication.isLoggedIn()) {
            Home h1 = new Home(action, this);
            h1.setVisible(true);
//            if(Authentication.hasPermission(new PermissionImpl(action))) {
//                h1.setVisible(false);
//                this.discountBtn.setEnabled(true);
//                this.jButton7.setEnabled(true);
//            }
        } else {
            this.discountBtn.setEnabled(true);
            this.jButton7.setEnabled(true);
            new Logout(this).setVisible(true);
//            if(!Authentication.hasPermission(new PermissionImpl(action))) {
//                this.discountBtn.setEnabled(false);
//                this.jButton7.setEnabled(false);
//            }
        }
    }//GEN-LAST:event_jButton6ActionPerformed

    private void billActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_billActionPerformed
        
        billObj.setVisible(true);
        //System.out.println("=============== >>> " + currOrder.getOrderId());
        billObj.setPurchasedItemList(purchasedItemList);
    }//GEN-LAST:event_billActionPerformed

    private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed
        clearUPC();
    }//GEN-LAST:event_btnClearActionPerformed

    private void btn7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn7ActionPerformed
        addCharacterToUPC("7");
    }//GEN-LAST:event_btn7ActionPerformed

    private void btn8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn8ActionPerformed
        addCharacterToUPC("8");
    }//GEN-LAST:event_btn8ActionPerformed

    private void btn4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn4ActionPerformed
        addCharacterToUPC("4");
    }//GEN-LAST:event_btn4ActionPerformed

    private void btn9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn9ActionPerformed
        addCharacterToUPC("9");
    }//GEN-LAST:event_btn9ActionPerformed

    private void btn6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn6ActionPerformed
        addCharacterToUPC("6");
    }//GEN-LAST:event_btn6ActionPerformed

    private void btn5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn5ActionPerformed
        addCharacterToUPC("5");
    }//GEN-LAST:event_btn5ActionPerformed

    private void btn1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn1ActionPerformed
        addCharacterToUPC("1");
    }//GEN-LAST:event_btn1ActionPerformed

    private void btn2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn2ActionPerformed
        addCharacterToUPC("2");
    }//GEN-LAST:event_btn2ActionPerformed

    private void btnDeleteLastCharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteLastCharActionPerformed
        removeLastUPCCharacter();
    }//GEN-LAST:event_btnDeleteLastCharActionPerformed

    private void btn3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn3ActionPerformed
        addCharacterToUPC("3");
    }//GEN-LAST:event_btn3ActionPerformed

    private void btn0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn0ActionPerformed
        addCharacterToUPC("0");
    }//GEN-LAST:event_btn0ActionPerformed

    private void ShippingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ShippingActionPerformed
     if(si != null){
        si.setVisible(true); 
     }
        
    }//GEN-LAST:event_ShippingActionPerformed

    /*
  
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Customer().setVisible(true);
            }
        });
    }
*/
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Shipping;
    private javax.swing.JLabel adSpace1;
    private javax.swing.JLabel adSpace2;
    private javax.swing.JLabel adSpace3;
    private javax.swing.JButton bill;
    private javax.swing.JButton btn0;
    private javax.swing.JButton btn1;
    private javax.swing.JButton btn2;
    private javax.swing.JButton btn3;
    private javax.swing.JButton btn4;
    private javax.swing.JButton btn5;
    private javax.swing.JButton btn6;
    private javax.swing.JButton btn7;
    private javax.swing.JButton btn8;
    private javax.swing.JButton btn9;
    private javax.swing.JButton btnClear;
    private javax.swing.JButton btnDeleteLastChar;
    private javax.swing.JButton clearAll;
    private javax.swing.JButton deleteBtn;
    public javax.swing.JButton discountBtn;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton6;
    public javax.swing.JButton jButton7;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables

    class TableSelectionListener implements ListSelectionListener {  
     
        public void valueChanged(ListSelectionEvent e) {
            if(e.getSource() == jTable1.getSelectionModel()){
                int i = jTable1.getSelectionModel().getMaxSelectionIndex();
                deleteBtn.setEnabled(true);
            }
        }
            
    }

    //Prepares objects and calls the discount dialog
    //The return value should be tested for NULL
    private PriceAdjustment openCustomerDiscountDialog() {

        //Check if there is a selected item
        int selectedRows[] = jTable1.getSelectedRows();

        //If no rows are selected, provide a message and return
        if (selectedRows.length < 1) {
            JOptionPane.showMessageDialog(this,
                    "Please select an item on which to apply a discount",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);

            return null;
        }
        //If more than one row selected, provide message and return
        else if (selectedRows.length > 1) {
            JOptionPane.showMessageDialog(this,
                    "A discount can only be applied to an individual item",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);

            return null;
        }

        //Given that a single row has been selected to apply a discount to:

        //Determine column number for relevant jTable fields
        int itemNameColumn = -1;
        int purchasedItemIdColumn = -1;

        //Check each column in the table for the appropriate name
        for (int colNum = 0; colNum <= jTable1.getColumnCount() - 1; colNum++){

            if (jTable1.getColumnName(colNum).equals("ItemName")) {
                itemNameColumn = colNum;
            }
            if (jTable1.getColumnName(colNum).equals("PItemId")) {
                purchasedItemIdColumn = colNum;
            }
        }

        //Confirm that columns were found, if not, provide message and return
        if (purchasedItemIdColumn == -1 ||
            itemNameColumn == -1) {

            JOptionPane.showMessageDialog(this,
                    "Design time error: Missing column",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);

            return null;
        }

        //Ensure valid item name value from JTable
        String itemName;

        //Validate the description
        if ((String)jTable1.getValueAt(selectedRows[0], itemNameColumn) == null) {
            itemName = "_NO NAME_";
        }
        else {
            itemName = (String)jTable1.getValueAt(selectedRows[0], itemNameColumn);
        }

        //Find the purchased item object that conforms to the currently selected
        //row in the jTable
        long purchasedItemId = (Long)jTable1.getValueAt(selectedRows[0], purchasedItemIdColumn);

        PurchasedItem selectedPurchasedItem = retrievePurchasedItem(purchasedItemId);

        //Instantiate a priceAdjustment object
        PriceAdjustment discount = new PriceAdjustment(
                pos.util.IDGenerator.getID(),
                0,
                1,
                PriceAdjustment.PriceAdjustmentType._NODESCRIPTION_,
                "_NO DESCRIPTION_",
                selectedPurchasedItem.getPurchaseItemId(),
                -1);

        //Create the dialog and open it
        CustomerDiscountDialog discountDialog = new CustomerDiscountDialog(
                this,
                true,
                discount,
                itemName,
                selectedPurchasedItem.getBasePrice() - selectedPurchasedItem.getPriceAdjustedAmount());

        discountDialog.setCustomer(this);
        discountDialog.setVisible(true);

        return discount;
    }

    //Find and return purchasedItem based on id
    //Check for null on return (failure)
    private PurchasedItem retrievePurchasedItem(Long purchasedItemId) {

        ListIterator purchItemListIter = purchasedItemList.listIterator();

        //Search list and return purchasedItem
        while (purchItemListIter.hasNext()) {
            
            PurchasedItem purchasedItem = (PurchasedItem)purchItemListIter.next();

            if (purchasedItem.getPurchaseItemId() == purchasedItemId) {

                return purchasedItem;
            }
        }

        //Method failed to find a purchased item
        return null;
    }

    //Add a price adjustment to a purchased item (based on purchasedItemId)
    //Returns true when the price adjustment has been added, false when the
    //method fails to find a purchased item
    private boolean addPriceAdjustmentToPurchasedItem(PriceAdjustment adjustment) {

        long adjPurchasedItemId = adjustment.getPurchasedItemId();

        ListIterator purchasedItemListIter = purchasedItemList.listIterator();

        // Search list and add the adjustment when a matching purchase item is found
        while (purchasedItemListIter.hasNext()) {

            //Get next item
            PurchasedItem purchasedItem = (PurchasedItem)purchasedItemListIter.next();

            //Purchased item match found
            if (purchasedItem.getPurchaseItemId() == adjPurchasedItemId) {

                //Add adjustment to purchased item
                purchasedItem.setPriceAdjustments(adjustment);
                return true;
            }
        }

        //No purchased item has been found if this point is reached
        return false;
    }

    //This method adds a single character to the end of the UPC field
    private void addCharacterToUPC(String characterToAppend) {

        //Ensure only one character is to be appended
        if (characterToAppend.length() > 1) {
            return;
        }

        //Get current text of the field
        String currentText = jTextField1.getText();

        //Append one character to the end of the string
        String appendedString = currentText + characterToAppend;

        //Reset the UPC field
        jTextField1.setText(appendedString);
    }

    //Clears the entire UPC text field
    private void clearUPC() {

        jTextField1.setText("");
    }

    //Removes the last character from the UPC field
    private void removeLastUPCCharacter() {

        //If UPC text has characters left
        String currUPC = jTextField1.getText();

        //Get UPC length
        int UPCLength = currUPC.length();

        if (UPCLength != 0) {

            String reducedUPC = currUPC.substring(0, UPCLength - 1);

            jTextField1.setText(reducedUPC);
        }
    }
}

